package com.lishe.lishe.lishe.module.search.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SimpleItemAnimator;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.ListPreloader;
import com.bumptech.glide.RequestBuilder;
import com.bumptech.glide.RequestManager;
import com.lishe.lishe.R;
import com.lishe.lishe.lishe.base.BaseActivity;
import com.lishe.lishe.lishe.bean.SpaceItemDecoration;
import com.lishe.lishe.lishe.bean.UserIntegralBean;
import com.lishe.lishe.lishe.common.AppManager;
import com.lishe.lishe.lishe.common.Globals;
import com.lishe.lishe.lishe.http.HttpImplements;
import com.lishe.lishe.lishe.module.main.activity.MainActivity0;
import com.lishe.lishe.lishe.module.main.event.TabChangeEvent;
import com.lishe.lishe.lishe.module.mall.activity.ClassifySearchActivity;
import com.lishe.lishe.lishe.module.search.adapter.SearchResultAdapter;
import com.lishe.lishe.lishe.module.search.bean.GoodsScreenBean;
import com.lishe.lishe.lishe.module.search.http.HttpSearch;
import com.lishe.lishe.lishe.utils.FormatUtil;
import com.lishe.lishe.lishe.utils.LoadingUtils;
import com.lishe.lishe.lishe.utils.LogUtil;
import com.lishe.lishe.lishe.utils.ToastUtil;
import com.lishe.lishe.lishe.utils.Utils;
import com.lishe.lishe.retrofit.DataResponseListener;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Bin
 * 分类商城
 */
public class SearchResultActivity extends BaseActivity implements View.OnClickListener {

    public static final String DESC = "desc";//倒序
    public static final String ASC = "asc";//正序
    private int mPage = 1;
    private String mPrice = "";
    private String mShop = "";
    private String mBind = DESC;
    private String mSold = "";
    private String mPriceRange = "";
    private String mCachePopShop = "";
    private String mKeyWord, mFrom;
    private SmartRefreshLayout mRefreshLayout;
    private RecyclerView mRecyclerView;
    private List<GoodsScreenBean.DataBean.ItemsBean> mList = new ArrayList<>();
    private RequestManager requestManager;
    private SearchResultAdapter commonAdapter;
    private View mEmptyLayout;
    private View mConditionLayout;
    private TextView mTvSynthesise;
    private TextView mTvSaleNum;
    private TextView mTvPrice;
    private ImageView mIvPriceImg;
    private TextView mTvScreen;
    private ImageView mIvScreenImg;
    private PopupWindow mScreenWindow;
    private TextView mPopJd;
    private TextView mPopLs;
    private EditText mPopPriceLow;
    private EditText mPopPriceHigh;
    private String mIntegral;//用户积分
    private View mErrorLayout;
    private View mTop;
    private int mCurrentY;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_searchresult);
        requestManager = Glide.with(this);
        mKeyWord = getIntent().getStringExtra(HomeSearchActivity.SEARCH_KEYWORD);
        mFrom = getIntent().getStringExtra(HomeSearchActivity.SEARCH_FROM);
        initView();
        getSearchData(Globals.TYPE_Edit);
        getUserIntegral(Globals.getToken());
    }

    private void initView() {
        TextView mTvKeyword = findViewById(R.id.keyword);
        mTvKeyword.setText(mKeyWord);
        mTop = findViewById(R.id.top);
        mTop.setOnClickListener(this);

        mRefreshLayout = findViewById(R.id.refreshlayout);
        mRefreshLayout.setEnableRefresh(false);
        mRefreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                mPage++;
                getSearchData(Globals.TYPE_LoadMore);
            }
        });

        mRecyclerView = findViewById(R.id.recyclerView);
        mRecyclerView.setLayoutManager(new GridLayoutManager(this, 2));
        ((SimpleItemAnimator) mRecyclerView.getItemAnimator()).setSupportsChangeAnimations(false);
        mRecyclerView.addItemDecoration(new SpaceItemDecoration(0, Utils.dip2px(context, 10), Utils.dip2px(context, 10), Utils.dip2px(context, 10)));
        commonAdapter = new SearchResultAdapter(this, mList);
//        // item图片预加载
//        FixedPreloadSizeProvider<GoodsScreenBean.DataBean.ItemsBean> preloadSizeProvider = new FixedPreloadSizeProvider<>(172, 172);
//        RecyclerViewPreloader preloader = new RecyclerViewPreloader<>(this, commonAdapter, preloadSizeProvider, 10);
//        mRecyclerView.addOnScrollListener(preloader);
        mRecyclerView.setAdapter(commonAdapter);
        //增加返回顶部按钮，当滑动达到第三屏的时候在屏幕右下角显示按钮
        mRecyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                mCurrentY += dy;
                if (mCurrentY > 4430) {
                    mTop.setVisibility(View.VISIBLE);
                } else {
                    mTop.setVisibility(View.GONE);
                }
            }
        });
        mErrorLayout = findViewById(R.id.error_layout);
        findViewById(R.id.error_retry).setOnClickListener(this);
        mEmptyLayout = findViewById(R.id.empty_layout);
        mConditionLayout = findViewById(R.id.condition_layout);
        //condition_layout
        //综合
        mTvSynthesise = findViewById(R.id.synthesise);
        mTvSynthesise.setOnClickListener(this);
        //销量
        mTvSaleNum = findViewById(R.id.sale_num);
        mTvSaleNum.setOnClickListener(this);
        //价格
        mTvPrice = findViewById(R.id.price);
        mIvPriceImg = findViewById(R.id.price_img);
        findViewById(R.id.ll_price).setOnClickListener(this);
        //筛选
        mTvScreen = findViewById(R.id.screen);
        mIvScreenImg = findViewById(R.id.screen_img);
        findViewById(R.id.ll_screen).setOnClickListener(this);

        findViewById(R.id.back).setOnClickListener(this);
        findViewById(R.id.govisit).setOnClickListener(this);
        findViewById(R.id.keyword_layout).setOnClickListener(this);
    }

    private void getUserIntegral(String token) {
        if (token == null) return;
        HttpImplements.getUserIntegral(token, new DataResponseListener<UserIntegralBean>() {
            @Override
            public void onSuccess(UserIntegralBean bean) {
                mIntegral = bean.getData().getBalance();
            }

            @Override
            public void onFail(String failMessage) {
            }

            @Override
            public void onError(Throwable e) {
            }
        });
    }

    public void getSearchData(final int type) {
        if (type != Globals.TYPE_LoadMore) {
            LoadingUtils.createLoadingDialog(this, "正在加载", false).show();
        }
        Map map = new HashMap();
        /*
        page	是	string	页码
        pageSize	是	string	每页显示数量
        keywords	是	string	搜索关键字
        bind	否	string	对商品的销量排序(只有desc)
        sold	否	string	对商品的销量排序(只有desc)
        price	否	string	对商品的价格排序((desc或者asc)
        shop	否	string	对商品的来源过滤(数据写法:0表示shop_id=10，即京东商品,1表示shop_id不为10和43,为礼舍自营)
        priceRange	否	string	对商品的价格区间过滤(使用的是人民币，如’10,30’表示查询价格为￥10到￥30元之间的商品)
        token	否	string	token
        */
        String token = Globals.getToken() == null ? "" : Globals.getToken();
        map.put("page", mPage + "");
        map.put("pageSize", "10");
        map.put("keywords", mKeyWord);
        map.put("price", mPrice);
        map.put("shop", mShop);
        map.put("bind", mBind);
        map.put("sold", mSold);
        LogUtil.i("mPriceRange", mPriceRange);
        map.put("priceRange", mPriceRange);
        map.put("token", token);
        HttpSearch.getGoodsScreen(map, new DataResponseListener<GoodsScreenBean>() {
            @Override
            public void onSuccess(GoodsScreenBean bean) {
                if (bean == null || bean.getData() == null) {
                    mRefreshLayout.setVisibility(View.GONE);
                    mEmptyLayout.setVisibility(View.VISIBLE);
                    setEmptyLayout(type);
                } else {
                    if (type != Globals.TYPE_LoadMore) {
                        mList.clear();
                    }
                    int start = mList.size();
                    mList.addAll(bean.getData().getItems());
                    commonAdapter.notifyDataSetChanged();
                    //commonAdapter.notifyItemRangeChanged(start, bean.getData().getItems().size());
                    if (mList.size() >= Integer.parseInt(bean.getData().getTotalCount())) {
                        mRefreshLayout.setLoadmoreFinished(true);
                    }
                    if (mList.size() != 0) {
                        mConditionLayout.setVisibility(View.VISIBLE);
                        mRefreshLayout.setVisibility(View.VISIBLE);
                        mEmptyLayout.setVisibility(View.GONE);
                    } else {
                        mRefreshLayout.setVisibility(View.GONE);
                        mEmptyLayout.setVisibility(View.VISIBLE);
                        setEmptyLayout(type);
                    }
                }
                if (type != Globals.TYPE_LoadMore) {
                    LoadingUtils.closeDialog();
                    mRecyclerView.scrollToPosition(0);
                }
                mRefreshLayout.finishLoadmore();
            }

            @Override
            public void onFail(String failMessage) {
                if (type != Globals.TYPE_LoadMore) {
                    LoadingUtils.closeDialog();
                }
                ToastUtil.showToast(SearchResultActivity.this, failMessage);
                mRefreshLayout.finishLoadmore();
            }

            @Override
            public void onError(Throwable e) {
                if (type != Globals.TYPE_LoadMore) {
                    LoadingUtils.closeDialog();
                    mRefreshLayout.setVisibility(View.GONE);
                    mConditionLayout.setVisibility(View.GONE);
                    mErrorLayout.setVisibility(View.VISIBLE);
                } else {
                    mPage--;
                }
                ToastUtil.showToast(SearchResultActivity.this, R.string.network_or_server_exception);
                mRefreshLayout.finishLoadmore();
            }
        });
    }

    private class MyPreloadModelProvider implements ListPreloader.PreloadModelProvider<GoodsScreenBean.DataBean.ItemsBean> {

        @NonNull
        @Override
        public List<GoodsScreenBean.DataBean.ItemsBean> getPreloadItems(int position) {
            //告诉RecyclerViewPreloader每个item项需要加载的图片url集合
            return mList.size() > 0 && position < mList.size() - 2 ? mList.subList(position, position + 1) : mList;
        }

        @Nullable
        @Override
        public RequestBuilder<?> getPreloadRequestBuilder(@NonNull GoodsScreenBean.DataBean.ItemsBean productsBean) {
            //返回一个加载图片的RequestBuilder（Glide内部的加载构建器）
            return requestManager.load(productsBean.getImage_default_id());
        }
    }

    private String popShop = "";

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.top:
                mCurrentY = 0;
                mTop.setVisibility(View.GONE);
                mRecyclerView.scrollToPosition(0);
                break;
            case R.id.error_retry:
                mErrorLayout.setVisibility(View.GONE);
                getSearchData(Globals.TYPE_Edit);
                break;
            case R.id.govisit:
                EventBus.getDefault().post(new TabChangeEvent(0));
                AppManager.getAppManager().back2Activty(MainActivity0.class);
                break;
            case R.id.keyword_layout:
                Intent i = new Intent(this, HomeSearchActivity.class);
                i.putExtra(HomeSearchActivity.SEARCH_KEYWORD, mKeyWord);
                i.putExtra(HomeSearchActivity.SEARCH_FROM, mFrom);
                startActivity(i);
                break;
            case R.id.back:
                if (mFrom != null && mFrom.equals("Classify")) {
                    AppManager.getAppManager().back2Activty(ClassifySearchActivity.class);
                } else {
                    AppManager.getAppManager().back2Activty(MainActivity0.class);
                }
                break;
            case R.id.synthesise:
                if (mBind == DESC) {
                    return;
                }
                mPage = 1;
                mBind = DESC;
                mSold = "";
                mPrice = "";
                mIvPriceImg.setImageResource(R.mipmap.value_icon);
                resetConTvColor(mTvSynthesise);
                getSearchData(Globals.TYPE_Condition);
                break;
            case R.id.sale_num:
                if (mSold == DESC) {
                    return;
                }
                mPage = 1;
                mSold = DESC;
                mBind = "";
                mPrice = "";
                mIvPriceImg.setImageResource(R.mipmap.value_icon);
                resetConTvColor(mTvSaleNum);
                getSearchData(Globals.TYPE_Condition);
                break;
            case R.id.ll_price:
                if (mPrice == DESC) {
                    mPrice = ASC;
                    mIvPriceImg.setImageResource(R.mipmap.value_up_icon);
                } else {
                    mPrice = DESC;
                    mIvPriceImg.setImageResource(R.mipmap.value_down_icon);
                }
                mPage = 1;
                mSold = "";
                mBind = "";
                resetConTvColor(mTvPrice);
                getSearchData(Globals.TYPE_Condition);
                break;
            case R.id.ll_screen:
                mIvScreenImg.setImageResource(R.mipmap.screen_up);
                mTvScreen.setTextColor(getResources().getColor(R.color.color_ff4138));
                showScreenPopUpWindow();
                break;
            /*---------------筛选弹窗-------------------------*/
            case R.id.jd_shop:
                if ("0".equals(mCachePopShop)) {
                    mCachePopShop = "";
                    mPopJd.setTextColor(getResources().getColor(R.color.gray_9));
                    mPopJd.setBackgroundResource(R.drawable.bg_15dp_corner_999999_stroke);
                    return;
                }
                mCachePopShop = "0";
                mPopLs.setTextColor(getResources().getColor(R.color.gray_9));
                mPopLs.setBackgroundResource(R.drawable.bg_15dp_corner_999999_stroke);
                mPopJd.setTextColor(getResources().getColor(R.color.color_ff4138));
                mPopJd.setBackgroundResource(R.drawable.bg_red_corner_15dp);
                break;
            case R.id.lishe_shop:
                if ("1".equals(mCachePopShop)) {
                    mCachePopShop = "";
                    mPopLs.setTextColor(getResources().getColor(R.color.gray_9));
                    mPopLs.setBackgroundResource(R.drawable.bg_15dp_corner_999999_stroke);
                    return;
                }
                mCachePopShop = "1";
                mPopJd.setTextColor(getResources().getColor(R.color.gray_9));
                mPopJd.setBackgroundResource(R.drawable.bg_15dp_corner_999999_stroke);
                mPopLs.setTextColor(getResources().getColor(R.color.color_ff4138));
                mPopLs.setBackgroundResource(R.drawable.bg_red_corner_15dp);
                break;
            case R.id.reset:
                mCachePopShop = "";
                mPopPriceLow.setText("");
                mPopPriceHigh.setText("");
                mPopLs.setTextColor(getResources().getColor(R.color.gray_9));
                mPopJd.setTextColor(getResources().getColor(R.color.gray_9));
                mPopLs.setBackgroundResource(R.drawable.bg_15dp_corner_999999_stroke);
                mPopJd.setBackgroundResource(R.drawable.bg_15dp_corner_999999_stroke);
                break;
            case R.id.sure:
                mShop = mCachePopShop;
                if ("".equals(mPopPriceLow.getText().toString()) && "".equals(mPopPriceHigh.getText().toString())) {
                    mPriceRange = "";
                } else {
                    //低价高于高价
                    if (!"".equals(mPopPriceLow.getText().toString()) && !"".equals(mPopPriceHigh.getText().toString())) {
                        if (Integer.parseInt(mPopPriceLow.getText().toString()) > Integer.parseInt(mPopPriceHigh.getText().toString())) {
                            String low = mPopPriceLow.getText().toString();
                            String high = mPopPriceHigh.getText().toString();
                            mPopPriceLow.setText(high);
                            mPopPriceHigh.setText(low);
                        }
                    }
                    mPriceRange = mPopPriceLow.getText().toString() + "," + mPopPriceHigh.getText().toString();
                }

                mScreenWindow.dismiss();
                mPage = 1;
                getSearchData(Globals.TYPE_Condition);
                break;
        }
    }

    private void setEmptyLayout(int type) {
        if (type == Globals.TYPE_Edit) {
            mConditionLayout.setVisibility(View.GONE);
            findViewById(R.id.govisit).setVisibility(View.VISIBLE);
        } else {
            mConditionLayout.setVisibility(View.VISIBLE);
            findViewById(R.id.govisit).setVisibility(View.GONE);
            TextView emptyText = findViewById(R.id.empty_text);
            emptyText.setText(R.string.condition_empty);
            TextView emptyAgain = findViewById(R.id.empty_again);
            emptyAgain.setText(R.string.condition_choseagain);
        }
    }

    private void showScreenPopUpWindow() {
        if (mScreenWindow == null) {
            View contentView = LayoutInflater.from(this).inflate(R.layout.popupwindow_screen, null);
            mScreenWindow = new PopupWindow(context);
            mScreenWindow.setContentView(contentView);
            mScreenWindow.setBackgroundDrawable(null);
            mScreenWindow.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
            mScreenWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
            //设置可以获取焦点，否则弹出菜单中的EditText是无法获取输入的
            mScreenWindow.setFocusable(true);
            mScreenWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
            // 设置允许在外点击消失
            mScreenWindow.setOutsideTouchable(true);

            mScreenWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    findViewById(R.id.GrayBG).setVisibility(View.GONE);
                    if ("".equals(mShop) && "".equals(mPriceRange)) {
                        mIvScreenImg.setImageResource(R.mipmap.screen);
                        mTvScreen.setTextColor(getResources().getColor(R.color.gray_3));
                    } else {
                        mIvScreenImg.setImageResource(R.mipmap.screen_red);
                        mTvScreen.setTextColor(getResources().getColor(R.color.color_ff4138));
                    }
                }
            });
            initPopView(contentView);
        }
        findViewById(R.id.GrayBG).setVisibility(View.VISIBLE);
        //相对某个控件的位置（正左下方），无偏移
        mScreenWindow.showAsDropDown(findViewById(R.id.line));
    }

    private void initPopView(View v) {
        mPopJd = v.findViewById(R.id.jd_shop);
        mPopJd.setOnClickListener(this);
        mPopLs = v.findViewById(R.id.lishe_shop);
        mPopLs.setOnClickListener(this);
        mPopPriceLow = v.findViewById(R.id.price_low);
        mPopPriceHigh = v.findViewById(R.id.price_high);
        if (mIntegral == null) {
            v.findViewById(R.id.integral_layout).setVisibility(View.GONE);
        } else {
            TextView integral = v.findViewById(R.id.myintegral);
            integral.setText(mIntegral);
            TextView money = v.findViewById(R.id.mymoney);
            money.setText("(等于¥" + FormatUtil.numFormat(Double.parseDouble(mIntegral) / 100) + ")");
        }
        v.findViewById(R.id.reset).setOnClickListener(this);
        v.findViewById(R.id.sure).setOnClickListener(this);
    }

    private void resetConTvColor(TextView tv) {
        mTvSynthesise.setTextColor(getResources().getColor(R.color.gray_3));
        mTvSaleNum.setTextColor(getResources().getColor(R.color.gray_3));
        mTvPrice.setTextColor(getResources().getColor(R.color.gray_3));
        tv.setTextColor(getResources().getColor(R.color.color_ff4138));
    }

}
